package com.fjwt.gz.task.mch;

import cn.hutool.core.date.DateUtil;
import com.alibaba.fastjson2.JSON;
import com.alibaba.fastjson2.JSONObject;
import com.fjwt.gz.core.exception.BizException;
import com.fjwt.gz.coupon.hkpay.HkpayCouponMerchantService;
import com.fjwt.gz.db.entity.AwardMchEntity;
import com.fjwt.gz.db.entity.MchChannelEntity;
import com.fjwt.gz.service.impl.SysConfigService;
import com.fjwt.gz.service.mapper.AwardCouponMapper;
import com.fjwt.gz.service.mapper.AwardMchMapper;
import com.fjwt.gz.service.mapper.MchChannelMapper;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.ObjectUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.*;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

@Slf4j
@Component
public class QueryUsableMerchantsTask {
    @Autowired
    private HkpayCouponMerchantService hkpayCouponMerchantService;
    @Autowired
    private AwardCouponMapper awardCouponMapper;
    @Autowired
    private MchChannelMapper mchChannelMapper;
    @Autowired
    private AwardMchMapper awardMchMapper;
    @Autowired
    private SysConfigService sysConfigService;

    /**
     * 调用海科接口对比已配置商户
     */
//    @Scheduled(cron = "${cron.QueryUsableMerchantsTask}")
    public void queryUsableMerchants() {
        /**
         * 可选优化方案：
         * 1.使用线程池，多线程处理
         * 2.使用局部缓存
         */
        ExecutorService executor = Executors.newFixedThreadPool(10);

        log.info("开始调用海科接口对比已配置商户任务,任务开始时间:{}", DateUtil.now());
        List<String> payConfigList = awardCouponMapper.queryPayConfigList();
        if (ObjectUtils.isEmpty(payConfigList)) {
            return;
        }
        //获取每个payConfigList集合中的payConfig中key为stockId的value作为集合
        List<String> stockIds = payConfigList.stream().map(payConfig -> JSON.parseObject(payConfig).getString("stockId")).toList();
        if (ObjectUtils.isEmpty(stockIds)) {
            return;
        }
        String authConfig = sysConfigService.getIfCode("hkpay");
        if (StringUtils.isBlank(authConfig)) {
            throw new BizException("海科接口参数有误");
        }
        for (String stockId : stockIds) {
            executor.submit(() -> {
                updateWechatSubmerchantNo(stockId, authConfig);
            });
        }
        executor.shutdown();
    }

    public void updateWechatSubmerchantNo(String stockId, String authConfig) {
        int offset = 0;
        while (true) {
            try {
                //微信间连号列表
                JSONObject reqJson = new JSONObject();
                reqJson.put("stockId", stockId);
                reqJson.put("offset", offset);
                reqJson.put("limit", 50);
                JSONObject jsonObject = hkpayCouponMerchantService.getMerchantList(reqJson, authConfig);
                if (ObjectUtils.isEmpty(jsonObject) || !jsonObject.containsKey("data")) {
                    throw new BizException("海科接口返回结果有误");
                }
                log.info("海科接口入参:{} ,海科接口返回结果:{}", stockId, jsonObject);
                //获取jsonObject中data的数据
                String data = jsonObject.getString("data");
                List<String> wechatSubmerchantNoList = JSON.parseArray(data, String.class);
                // 批量查询 mchChannelEntity
                List<MchChannelEntity> mchChannelEntities = mchChannelMapper.selectList(
                        MchChannelEntity.gw()
                                .in(MchChannelEntity::getWechatSubmerchantNo, wechatSubmerchantNoList)
                );
                // 将微信间连号列表分组，key为商户号，value为微信间连号列表
                if (ObjectUtils.isEmpty(mchChannelEntities)) {
                    return;
                }
                Map<String, Set<String>> map = mchChannelEntities.stream()
                        .collect(HashMap::new, (m, v) -> m.computeIfAbsent(v.getMchNo(), k -> new HashSet<>()).add(v.getWechatSubmerchantNo()), HashMap::putAll);
                //  封装
                List<AwardMchEntity> newList = new ArrayList<>();
                for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
                    String mchNo = entry.getKey();
                    Set<String> wSNSet = entry.getValue();
                    String wechatSubmerchantNo = String.join(",", wSNSet);
                    AwardMchEntity awardMchEntity = new AwardMchEntity();
                    awardMchEntity.setMchNo(mchNo);
                    awardMchEntity.setWechatSubmerchantNo(wechatSubmerchantNo);
                    newList.add(awardMchEntity);
                }
                if (newList.size() > 0) {
                    log.info("批量更新商户号对应的微信间连号:{}", newList);
                    awardMchMapper.updateBatchWechatSubmerchantNoByMchNo(newList);
                }
                Integer totalCount = jsonObject.getInteger("totalCount");
                int page = (int) Math.ceil((double) totalCount / 50);
                log.info("stockId{},总页码数{},当前页{}", stockId, page, offset+1);
                if (offset >= page - 1) {
                    return;
                }
                Thread.sleep(6000);
                offset++;
            } catch (BizException e) {
                log.error("error", e.getMessage());
                return;
            } catch (Exception e) { //出现异常，直接退出，避免死循环。
                log.error("error", e);
                return;
            }
        }
    }
}
